package com.rabbit.framework.mybatisplus;

import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.rabbit.common.core.domain.model.LoginUser;
import com.rabbit.common.exception.ServiceException;
import com.rabbit.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * MP注入处理器
 *
 * @author Lion Li
 * @date 2021/4/25
 */
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {
    /**
     * 创建时间
     */
    public static final String CREATE_TIME = "createTime";
    /**
     * 创建者
     */
    public static final String CREATE_BY = "createBy";
    /**
     * 修改时间
     */
    public static final String UPDATE_TIME = "updateTime";
    /**
     * 修改者
     */
    public static final String UPDATE_BY = "updateBy";


    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            //根据属性名字设置要填充的值
            if (metaObject.hasGetter(CREATE_TIME)) {
                this.setFieldValByName(CREATE_TIME, new Date(), metaObject);
            }
            if (metaObject.hasGetter(CREATE_BY)) {
                this.setFieldValByName(CREATE_BY, getLoginUsername(), metaObject);
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
        updateFill(metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (metaObject.hasGetter(UPDATE_BY)) {
                this.setFieldValByName(UPDATE_BY, getLoginUsername(), metaObject);
            }
            if (metaObject.hasGetter(UPDATE_TIME)) {
                this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    /**
     * 获取登录用户名
     */
    private String getLoginUsername() {
        LoginUser loginUser;
        try {
            loginUser = SecurityUtils.getLoginUser();
        } catch (Exception e) {
            log.error("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUser.getUsername();
    }

}
